<template>
	<view>
		<view class="page__content">
			<up-navbar :fixed="false" title="派工单" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</up-navbar>

			<view class="page__content__top">
				<view class="x-bc" style="padding: 10px;background-color: #f9f9f9;">
					<text style="font-size: 28rpx;font-weight: 600;">基础信息</text>

					<text style="font-size: 24rpx;color: #6b88ff"
						@click="changeFormType">{{config.showForm ? "折叠" : "展开"}}</text>
				</view>
			</view>

			<view class="page__content__main" id="page__content__main">
				<view class="form" v-show="config.showForm">

					<up-form labelPosition="left" :model="formData" :rules="rules" ref="baseFormRef">
						<up-form-item labelWidth="100" label="派工日期" prop="BillDate" borderBottom leftIcon="file-text"
							required :leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView" @click="choiceTime('BillDate')">
								<up-input v-model="formData.BillDate" readonly placeholder="请选择"
									border="none"></up-input>
							</view>

							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<up-form-item labelWidth="100" label="派工类型" prop="TypeName" borderBottom leftIcon="file-text"
							required :leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView" @click="openBaseScreen('派工类型','radio')">
								<up-input v-model="formData.TypeName" readonly placeholder="请选择"
									border="none"></up-input>
							</view>

							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>


						<template v-if="config.isEdit">
							<up-form-item labelWidth="100" label="来源工单" prop="WoBillNO" borderBottom
								leftIcon="file-text" required :leftIconStyle="{'font-size':'40rpx'}">
								<view class="iptView">
									<up-input v-model="formData.WoBillNO" readonly border="none"></up-input>
								</view>
							</up-form-item>

							<up-form-item labelWidth="100" label="派工单号" prop="BillNO" borderBottom leftIcon="file-text"
								:leftIconStyle="{'font-size':'40rpx'}">
								<view class="iptView">
									<up-input v-model="formData.BillNO" readonly border="none"></up-input>
								</view>
							</up-form-item>
						</template>

						<template v-else>
							<up-form-item labelWidth="100" label="来源工单" prop="BillNO" borderBottom leftIcon="file-text"
								required :leftIconStyle="{'font-size':'40rpx'}">
								<view class="iptView">
									<up-input v-model="formData.BillNO" readonly border="none"></up-input>
								</view>
							</up-form-item>
						</template>

						<up-form-item labelWidth="100" label="产品名称" borderBottom leftIcon="file-text"
							:leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView">
								<up-input v-model="formData.ProductName" readonly border="none"></up-input>
							</view>
						</up-form-item>

						<up-form-item labelWidth="100" label="产品规格" borderBottom leftIcon="file-text"
							:leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView">
								<up-input v-model="formData.ProductSpec" readonly border="none"></up-input>
							</view>
						</up-form-item>

						<up-form-item labelWidth="100" label="计划数" prop="FPlanQty" borderBottom leftIcon="coupon"
							required :leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView">
								<up-input v-model="formData.FPlanQty" type="number" placeholder="请输入"
									border="none"></up-input>
							</view>

							<template #right>
								<up-icon name="edit-pen-fill"></up-icon>
							</template>
						</up-form-item>

						<up-form-item labelWidth="100" label="工艺路线" prop="Routing" borderBottom leftIcon="share"
							required :leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView" @click="openBaseScreen('工艺路线','other')">
								<up-input v-model="formData.Routing" readonly placeholder="请选择"
									border="none"></up-input>
							</view>

							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<up-form-item labelWidth="120" label="计划开始时间" :borderBottom="true" leftIcon="coupon" required
							:leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView" @click="choiceTime('start')" style="font-size: 28rpx;">
								<text>{{dateFormat(formData.DueStartDate) }}</text>
							</view>
						</up-form-item>
						<up-form-item labelWidth="120" label="计划结束时间" :borderBottom="true" leftIcon="coupon" required
							:leftIconStyle="{'font-size':'40rpx'}">
							<view class="iptView" @click="choiceTime('end')" style="font-size: 28rpx;">
								<text>{{dateFormat(formData.DueEndDate) }}</text>
							</view>
						</up-form-item>

					</up-form>

				</view>
				<up-sticky>
					<view id="sticky-box">
						<view class="x-f">
							<view class="assignVal">
								<text>设备指派</text>
							</view>
							<up-switch v-model="config.assignVal" @change="changeAssign"></up-switch>
						</view>

						<view v-if="config.assignVal" class="setps__box">
							<!-- <up-steps :current="stepsCurrent">
							<up-steps-item style="min-width: 100rpx;" v-for="(item,index) in RoutingData" :key="index"
								@click="changeCurrent(item,index)" :title="item.ProcedureName"
								:desc="!item.Outsource ? '厂内' :'外协'">
							</up-steps-item>
						</up-steps> -->

							<m-steps :steps="RoutingData" :currentStep="stepsCurrent"
								:formmat="{ title:'ProcedureName' }" @change="changeCurrent">
								<template #desc="{element}">
									<text>{{ !element.Outsource ? '厂内' :'外协' }}</text>
								</template>
							</m-steps>


							<view class="x-bc">
								<view class="x-f" style="margin-top: 10rpx;padding: 10rpx;">
									<button type="primary" style="width: fit-content;margin-right: 6px !important;"
										size="mini" @click="tableDataByFun('add')">新增</button>
									<button type="warn" style="width: fit-content;" size="mini"
										@click="tableDataByFun('del')">删除</button>
								</view>


								<view style="font-size: 12px;color: #999;" v-if="formData.FPlanQty">
									<text>剩余可分配：</text>
									<text>{{ (formData.FPlanQty - EQFPlanQty_sum) || 0 }}</text>
								</view>
							</view>
						</view>
					</view>
				</up-sticky>



				<zb-table v-show="config.assignVal" :show-header="true" :columns="tableColumns" :stripe="true"
					:fit="false" show-summary sum-text="合计" @cellClick="handleCellClick" :summary-method="getSummaries"
					:border="true" :data="tableData" :height="`calc(100% - ${stickyHeight}px)`"></zb-table>


			</view>


			<view class="page__content__bottom" :style="uni.$utils.disposeSafeBottomFun()">
				<button class="content_bottom_primary_Btn" style="width: 90%;margin: 0 auto !important;"
					@click="saveRow">提交</button>
			</view>

		</view>


		<up-datetime-picker ref="datetimePicker" :title="timePickerConfig.pickerTitle"
			:show="timePickerConfig.showTimePicker" v-model="timePickerConfig.datetimeData" mode="date"
			:closeOnClickOverlay="true" @close="closePicker" @cancel="closePicker" @confirm="confirmTime"
			:formatter="formatter"></up-datetime-picker>

	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed, getCurrentInstance, watch } from 'vue'
	import { onLoad, onReady, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();
	// import mZbTable from '../components/zb-table/zb-table';
	import mSteps from '../components/m-steps/m-steps';


	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	});


	let config = reactive<any>({
		isEdit: false,// 判断当前页状态
		showForm: true, // 判断是否展示主表区域
		assignVal: false, // 是否指派
	});
	function changeFormType() {
		config.showForm = !config.showForm;
	}
	// 切换是否指派
	function changeAssign(val : any) {
		config.assignVal = val;
	}

	let formData = reactive<any>({
		BillDate: '', // 派工日期
		TypeName: '',
		TypeCode: '',
		JobDocTypeID: null,
		JobOrderID: '',
		BillNO: '',
		WoOrderID: '',
		ProductName: '',
		ProductID: '',
		ProductSpec: '',
		FPlanQty: 0, // 派工数 
		Routing: '', // 工艺路线显示字段
		FWorkshopID: '',
	});

	let rules = {
		TypeName: {
			type: 'string',
			required: true,
			message: '请选择派工类型',
			trigger: ['change']
		},
		BillNO: {
			type: 'string',
			required: true,
			message: '请选择来源工单',
			trigger: ['change']
		},
		FPlanQty: {
			type: 'number',
			required: true,
			message: '请输入计划数',
			trigger: ['blur', 'input']
		},
		Routing: {
			type: 'string',
			required: true,
			message: '请定义工艺路线',
			trigger: ['change'],
		}
	}

	interface UFormsInstance {
		validate : (callback ?: (isValid : boolean) => void) => Promise<boolean>
		resetFields : () => void
	}
	const baseFormRef = ref<UFormsInstance | any>(null);

	let foundNode = ref<any>(null);
	// 获取页面按钮权限
	for (const module of permissionStore.moduleInfoAll) {
		if (module.TreeTypeName === '生产管理') {
			for (const node of module.Node) {
				if (node.APFunName === '新建派工') {
					foundNode.value = JSON.parse(JSON.stringify(node));
					break; // 找到后立即退出内层循环  
				}
			}
			if (foundNode.value) {
				break;
			}
		}
	};

	let btnApprove = ref<any>(null)
	btnApprove.value = uni.$utils.isEmpty(foundNode.value) ? [] : foundNode.value['IconApprove'];


	let routes = getCurrentPages(); //当前页面栈
	// 子表下拉选监听器
	const formBaseScreenListenName = computed(() => {
		return 'createTicet_choice_form_' + routes.length
	});
	// 子表下拉选监听器
	const childBaseScreenListenName = computed(() => {
		return 'createTicet_choice_child_' + routes.length
	});

	// 底部按钮区域功能 -- Start
	// 按钮权限映射
	function ApproveBack(str : string) {
		let Type = btnApprove.value.some((item : any) => {
			return item.MenuName == str
		})

		return Type;
	};
	function isToday(dateString : any) { // 判断是否为当日
		// 假设dateString是一个格式为"YYYY-MM-DD"的字符串  
		const today = new Date();
		const inputDate = new Date(dateString);

		// 清除时间部分  
		today.setHours(0, 0, 0, 0);
		inputDate.setHours(0, 0, 0, 0);

		// 直接比较年份、月份和日期  
		return (
			today.getFullYear() === inputDate.getFullYear() &&
			today.getMonth() === inputDate.getMonth() &&
			today.getDate() === inputDate.getDate()
		);
	};
	// 提交按钮
	function saveRow() {
		// 校验主表
		baseFormRef.value.validate().then(async (ret : any) => {

			// 调用切换事件，存储当前工序数据
			changeCurrent({}, stepsCurrent.value);

			await uni.$utils.sleep(100);

			// 校验子表
			// 1、判断是否开启指派
			if (config.assignVal) {
				console.log(RoutingData.value);
				// 判断所有子表是否都没有数据
				let hasNotAllEmpty = RoutingData.value.every((item : any) => !item.TableData.length)
				if (hasNotAllEmpty) {
					return uni.$utils.layer.alert("当前已开启设备指派，请至少选择一道工序进行指派！")
				}

			}
			// 数据是否超过计划数量


			let Flash = false;

			// 遍历工艺路线
			for (let i = 0; i < RoutingData.value.length; i++) {
				const item = RoutingData.value[i];

				// 遍历指定工艺工序下的表格数据
				for (let j = 0; j < item.TableData.length; j++) {
					const row = item.TableData[j];
					// 查询是否有未填写的设备
					if (uni.$utils.isEmpty(row['EquipmentID'])) {
						uni.$utils.layer.alert('请完善设备选项');

						changeCurrent({}, i);
						Flash = true;
						break;
					};
					if (uni.$utils.isEmpty(row["EQFPlanQty"])) {
						uni.$utils.layer.alert('请给设备分配数量');

						changeCurrent({}, i);
						Flash = true;
						break;
					}
				};
				if (Flash) {
					break;
				};
			};
			if (Flash) {
				return;
			};
			uni.$utils.showLoading();
			let EquipmentTypeID = [],
				Outsource = [], // 是否外协
				WoPROCID = [],
				ProcedureID = [],
				EquipmentID = [],
				JobPROCID = [], // 子表主键ID
				JobFWorkshopID = [],
				MoludTypeID = [],
				MoludID = [],
				ProcessRouteID = [],
				LabourCost = [],
				ProcessRouteDeID = [],
				HourGJ = [],
				ManHour = [],
				FProcessMan = [];

			// 子子表数据
			let EQFlowOrder = [],
				EQProcedureID = [],
				EQOutsource = [],
				EQLabourCost = [],
				EQManHour = [],
				EQHourGJ = [],
				EQEquipmentID = [],
				EQMoludID = [],
				EQFPlanQty = [],
				EQJobDocTypeID = [],
				JobPROCAssignEQID = [];

			for (let i = 0; i < RoutingData.value.length; i++) {
				let item = RoutingData.value[i];
				Outsource.push(item.Outsource ? 1 : 0);
				WoPROCID.push(item.WoPROCID || 0);
				ProcedureID.push(item.ProcedureID || 0);
				EquipmentTypeID.push(item.EquipmentTypeID || 0);
				EquipmentID.push(item.EquipmentID || 0);
				JobFWorkshopID.push(item.FWorkshopID || 0);
				JobPROCID.push(uni.$utils.isEmpty(item.JobPROCID) ? 0 : item.JobPROCID);
				MoludTypeID.push(item.MoludTypeID || 0);
				MoludID.push(item.MoludID || 0);
				ProcessRouteID.push(item.ProcessRouteID || 0);
				LabourCost.push(item.LabourCost || 0);
				ProcessRouteDeID.push(item.ProcessRouteDeID || 0);
				HourGJ.push(item.HourGJ || 0);
				ManHour.push(item.ManHour || 0);
				FProcessMan.push(item.EmplID || 0);

				if (!item.Outsource) {

					if (!uni.$utils.isEmpty(item.TableData)) {

						for (let j = 0; j < item.TableData.length; j++) {
							let row = item.TableData[j];
							EQFlowOrder.push((i + 1));
							EQProcedureID.push(item.ProcedureID);
							EQOutsource.push(0);
							EQLabourCost.push(0);
							EQManHour.push(0);
							EQHourGJ.push(0);
							EQMoludID.push(0);
							EQEquipmentID.push(row.EquipmentID);
							EQFPlanQty.push(row.EQFPlanQty);
							EQJobDocTypeID.push(row.JobDocTypeID);
							JobPROCAssignEQID.push(row.JobPROCAssignEQID ? row.JobPROCAssignEQID : 0);

						}
					} else {
						EQFlowOrder.push((i + 1));
						EQProcedureID.push(item.ProcedureID);
						EQOutsource.push(0);
						EQLabourCost.push(0);
						EQManHour.push(0);
						EQHourGJ.push(0);
						EQMoludID.push(0);

						EQEquipmentID.push(0);
						EQFPlanQty.push(0);
						EQJobDocTypeID.push(0);
						JobPROCAssignEQID.push(0);
					}

				}

			};

			let type = 'Y-MM-dd';
			let BillDate = null;
			if (isToday(formData.BillDate)) {
				type = 'Y-MM-dd hh:mm:ss';
			} else {
				BillDate = formData.BillDate;
			}
			BillDate = dateFormat(BillDate, type);






			let obj = {
				WoOrderID: formData.WoOrderID,
				JobDocTypeID: formData.JobDocTypeID,
				ProductID: formData.ProductID,
				JobOrderID: formData.JobOrderID || 0,
				FPlanQty: formData.FPlanQty || 0,
				BillDate: BillDate,
				DueStartDate: dateFormat(formData.DueStartDate),
				DueEndDate: dateFormat(formData.DueEndDate),
				Outsource: Outsource.join('~'), // 是否外协

				JobPROCID: JobPROCID.join('~'),
				EquipmentTypeID: EquipmentTypeID.join('~'), // 设备类型
				WoPROCID: WoPROCID.join('~'), // 工单工序ID
				ProcedureID: ProcedureID.join('~'), // 工序ID
				EquipmentID: EquipmentID.join('~'), // 设备
				JobFWorkshopID: JobFWorkshopID.join('~'), // 工序车间
				MoludTypeID: MoludTypeID.join('~'), // 模具类型
				MoludID: MoludID.join('~'), // 模具
				ProcessRouteID: ProcessRouteID.join('~'), // 工艺路线主表ID
				LabourCost: LabourCost.join('~'), // 工价
				ProcessRouteDeID: ProcessRouteDeID.join('~'), // 工艺路线子表ID
				HourGJ: HourGJ.join('~'), // 工时工价
				ManHour: ManHour.join('~'), // 工时
				FProcessMan: FProcessMan.join('~'), // 生产人员
				EQFlowOrder: EQFlowOrder.join('~'),
				EQProcedureID: EQProcedureID.join('~'),
				EQOutsource: EQOutsource.join('~'),
				EQLabourCost: EQLabourCost.join('~'),
				EQManHour: EQManHour.join('~'),
				EQHourGJ: EQHourGJ.join('~'),
				EQEquipmentID: EQEquipmentID.join('~'),
				EQMoludID: EQMoludID.join('~'),
				EQFPlanQty: EQFPlanQty.join('~'),
				EQJobDocTypeID: EQJobDocTypeID.join('~'),
				JobPROCAssignEQID: JobPROCAssignEQID.join('~')
			};

			console.log(obj);

			request({
				config: {
				},
				url: 'XGD_JobSuborUpDte_2',
				method: 'POST',
				data: obj,
				success(ret : any) {
					if (ret.status == 200) {

						if (ret.data.ds[0]['status'] == 500) {

							uni.$utils.hideLoading();
							uni.$utils.layer.alert(ret.data.ds[0]['msg']);

						} else {


							uni.$utils.hideLoading();
							uni.showToast({
								title: '保存成功'
							});
							// 接口请求成功后将页面状态改为edit，并调用回显接口
							config.isEdit = 'edit';
							formData.JobOrderID = ret.data.ds[0]['JobOrderID'];
							getDispatchInfo('all');

							// 刷新派工单列表
							uni.$emit('refreshPage_dispatch');
						}
					} else {
						uni.$utils.hideLoading();
					}
				},
				fail(err : any) {
					uni.$utils.hideLoading();
				}
			})


		}).catch((error : any) => {
			console.log(error);
			uni.$utils.hideLoading();
			uni.$utils.layer.alert('请完善表单信息！');
		})
	}
	// 底部按钮区域功能 -- End


	// 主表事件 -- Start
	// 时间映射
	function dateFormat(val ?: any, type = 'Y-MM-dd') { // 格式化时间

		if (!uni.$utils.isEmpty(val)) {
			return uni.$utils.dateFormat(new Date(val), type);
		} else {
			return uni.$utils.dateFormat(new Date(), type);
		}
	}

	// 点击的时间选项

	let timePickerConfig = reactive<any>({
		timeType: null,
		datetimeData: null,
		pickerTitle: null,
		showTimePicker: false,
	});
	// 时间选择器数据格式化
	const formatter = (type : any, value : any) => {
		let backValue = ""
		switch (type) {
			case "year":
				backValue = value + "年";
				break;
			case "month":
				backValue = value + "月";
				break;
			case "day":
				backValue = value + "日";
				break;
			default:
				break;
		};

		return backValue;
	}
	// 时间选择
	function choiceTime(type : any) {
		timePickerConfig.timeType = type;

		switch (type) {
			case "start":
				timePickerConfig.datetimeData = Number(new Date(formData.DueStartDate));
				timePickerConfig.pickerTitle = "计划开始时间";
				break;
			case "end":
				timePickerConfig.datetimeData = Number(new Date(formData.DueEndDate));
				timePickerConfig.pickerTitle = "计划结束时间";
				break;
			case "BillDate":
				timePickerConfig.datetimeData = Number(new Date(formData.BillDate));
				timePickerConfig.pickerTitle = "派工日期";
				break;
			default:
				timePickerConfig.datetimeData = Number(new Date());
				timePickerConfig.pickerTitle = "";
				break;
		};

		timePickerConfig.showTimePicker = true;
	};
	// 关闭时间选择器
	const closePicker = () => {
		timePickerConfig.datetimeData = Number(new Date());
		timePickerConfig.showTimePicker = false;
	};
	// 确认时间选择器
	const confirmTime = (data : any) => {
		switch (timePickerConfig.timeType) {
			case "start":
				formData.DueStartDate = data.value;
				break;
			case "end":
				formData.DueEndDate = data.value;
				break;
			case "BillDate":
				formData.BillDate = dateFormat(data.value);
				break;
			default:
				break;
		};
		timePickerConfig.showTimePicker = false;
	};

	// 前往下拉选
	function openBaseScreen(str : string, type : string) {
		const multiple = type == "check";
		console.log(multiple);
		switch (str) {
			case "派工类型":
				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'XGD_JobType', // 接口名
					titleName: str,
					listeningName: formBaseScreenListenName.value, // 监听器
					multiple: multiple, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "TypeName", // 显示值
							hiddenValue: "JobDocTypeID", // 隐藏值
						},
						subText: [{
							label: "编号", // label文本
							labelKey: "TypeCode", // 显示label文本后文字的key
						}],
						isPaging: false, //是否分页
						choiceData: formData.JobDocTypeID, // 选中数据
						choiceDataKey: "JobDocTypeID", // 选中数据的key
					},
					param: { // 传递参数
					}
				});
				break;
			case "产品":
				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'XGD_Product', // 接口名
					titleName: str,
					listeningName: formBaseScreenListenName.value, // 监听器
					multiple: multiple, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "SearchKey", // 显示值
							hiddenValue: "ProductInfo", // 隐藏值
							pageIndex: "PageIndex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						choiceData: formData.ProductInfo, // 选中数据
						choiceDataKey: "ProductInfo", // 选中数据的key
					},
					param: { // 传递参数
						SearchKey: '',
						PageIndex: 1,
						PageSize: 30
					}
				});
				break;
			case "来源工单":
				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'XGD_GetWorkByJobType', // 接口名
					titleName: str,
					listeningName: formBaseScreenListenName.value, // 监听器
					multiple: multiple, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "BillNO", // 显示值
							hiddenValue: "WoOrderID", // 隐藏值
						},
						subText: [{
							label: "产品",
							labelKey: "ProductName",
						}, {
							label: "可派数量",
							labelKey: "KFPlanQty",
						}],
						isPaging: false, //是否分页
						choiceData: formData.WoOrderID, // 选中数据
						choiceDataKey: "WoOrderID", // 选中数据的key
					},
					param: { // 传递参数
						JobDocTypeID: formData.JobDocTypeID
					}
				});
				break;
			case "工艺路线":
				mainStore.BaseScreenParm = {
					RoutingData: RoutingData.value,
					formData: formData,
					listenName: formBaseScreenListenName.value
				};
				uni.navigateTo({
					url: '/st_ticket/page_dispatch/dispatch-routing'
				});
				break;
			default:
				break;
		}

	}
	// 主表事件 -- End

	// 工艺路线
	let RoutingData = ref<any>([]);

	// 选中工序索引
	let stepsCurrent = ref<number>(0);
	// 表格数据
	let tableData = ref<any>([]);
	// 表格头部
	let tableColumns = ref<any>([
		// 复选框列
		{ type: 'selection', fixed: true, width: 50 },
		{ label: '派工类型', name: 'TypeName', width: 80 },
		{ label: '设备', name: 'EquipmentCode', width: 200 },
		{ label: '分配数', name: 'EQFPlanQty', width: 80 },
	]);

	// 
	let EQFPlanQty_sum = ref(0);

	// 表格合计方法定义
	const getSummaries = ({ column, data } : any) => {
		// console.log(data);
		if (!data.length) return ['', '', '', '']

		let sum = data.reduce((total : number, item : any) => {
			return total + +item["EQFPlanQty"];
		}, 0);

		// 赋值分配数合计数据
		EQFPlanQty_sum.value = sum;

		return ['', '', '', String(sum)]
	};

	// 用于表格的下拉选方法
	const openBaseScreen_Table = (str : string) => {
		switch (str) {
			case "设备":
				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'PGD_GetEquipment', // 接口名
					titleName: str,
					listeningName: childBaseScreenListenName.value, // 监听器
					multiple: false, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "EquipmentCode", // 显示值
							hiddenValue: "EquipmentID", // 隐藏值
						},
						isPaging: false, //是否分页
						searchKey: 'EquipmentCode', //搜索关键词，应包含在param中
						choiceData: tableData.value[clickCellInfo.index].EquipmentID, // 选中数据
						choiceDataKey: "EquipmentID", // 选中数据的key
					},
					param: { // 传递参数
						EquipmentTypeID: 0, // 类型ID
						EquipmentCode: '', // 筛选条件
						EquipmentID: 0, // 设备ID
					}
				});
				break;
			case "派工类型":
				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'XGD_JobType', // 接口名
					titleName: str,
					listeningName: childBaseScreenListenName.value, // 监听器
					multiple: false, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "TypeName", // 显示值
							hiddenValue: "JobDocTypeID", // 隐藏值
						},
						subText: [{
							label: "编号", // label文本
							labelKey: "TypeCode", // 显示label文本后文字的key
						}],
						isPaging: false, //是否分页
						choiceData: tableData.value[clickCellInfo.index].JobDocTypeID, // 选中数据
						choiceDataKey: "JobDocTypeID", // 选中数据的key
					},
					param: { // 传递参数
					}
				});
				break;
			default:
				break;
		}
	}
	// 表格选中行数据
	let clickCellInfo = reactive<any>({
		row: null,
		index: null,
		column: null,
	});
	// 表格行点击事件
	function handleCellClick(row : any, index : number, column : any) {
		// 记录点击的单元格信息
		Object.assign(clickCellInfo, {
			row,
			index,
			column
		});
		console.log(clickCellInfo);

		switch (column.label) {
			case "派工类型":
			case "设备":
				openBaseScreen_Table(column.label);
				break;
			case "分配数":
				uni.$utils.layer.prompt({
					title: "请输入分配数"
				}, (ret : any) => {
					console.log(ret.action);
					switch (ret.action) {
						case "confirm":
							if (!uni.$utils.isEmpty(ret.value)) {
								const result = ret.value;
								tableData.value[clickCellInfo.index]["EQFPlanQty"] = result;
							}
							break;
						default:
							break;
					}
				})
				break;
			default:
				break;
		}

	}

	// 表格新增删除
	const tableDataByFun = (action : "add" | "del") => {
		// 直接复制一份，不要重复定义 ref<any>([]) 再覆盖
		let newTableData = [...tableData.value];

		if (action === "add") {
			const currentRouting = RoutingData.value[stepsCurrent.value];

			// 已报工, 且无指派记录，不允许添加
			if (
				uni.$utils.isEmpty(currentRouting) ||
				(currentRouting?.WCQty > 0 && currentRouting?.TableData?.length === 0)
			) {
				return uni.$utils.layer.alert("该工序【未指派】且【已报工】，不允许添加");
			}

			// 添加唯一标识，避免使用索引作为 rowKey
			const tempId = `temp_${Date.now()}`;
			newTableData.push({
				id: tempId,
				TypeName: "派工单",
				TypeCode: "",
				JobDocTypeID: 1,

				EquipmentID: "",
				EquipmentCode: "",
				EquipmentName: "",
				EquipmentSpec: "",

				EQFPlanQty: "", // 指定计划数量
			});
		}

		if (action === "del") {
			// tableData 带有 checked 字段，过滤掉已选中项
			newTableData = tableData.value.filter((item : any) => !item.checked);
		}

		// 重新计算 index
		tableData.value = newTableData.map((item, index) => ({
			...item,
			index,
		}));
	};

	// 切换指派工序
	function changeCurrent(data : any, index : number) {
		if (RoutingData.value[index]['Outsource']) {
			return uni.$utils.layer.alert(RoutingData.value[index]['ProcedureName'] + '为外协工序，不可指派该道工序')
		}

		RoutingData.value[stepsCurrent.value]['TableData'] = JSON.parse(JSON.stringify(tableData.value));
		setTimeout(() => {
			stepsCurrent.value = index;
			// 清除可分配数数据
			EQFPlanQty_sum.value = 0;
			// 赋值选中的表格数据
			tableData.value = RoutingData.value[index].TableData.map((item : any, index : number) => {
				return {
					...item,
					index
				}
			});
		}, 100)
	};


	// 回显接口，获取详情
	function getDispatchInfo(str ?: any) {
		request({
			config: {
			},
			url: 'XGD_SelectJonbDetails',
			method: 'POST',
			data: {
				JobOrderID: formData.JobOrderID
			},
			success(ret : any) {
				console.log(ret);
				if (ret.status == 200) {
					ret.data.ds[0]['BillDate'] = dateFormat(ret.data.ds[0]['BillDate'], 'Y-MM-dd hh:mm:ss');
					Object.assign(formData, ret.data.ds[0]);
					let FunData = JSON.parse(JSON.stringify(ret.data.ds1));
					const FilterData = ret.data.ds1.map((item : any) => item.ProcedureName);

					switch (str) {
						case "all":
							formData.Routing = FilterData.join(',');

							FunData.forEach((item : any) => {
								item['TableData'] = [];

								ret.data.ds2.forEach((row : any) => {
									row['EQFPlanQty'] = row['FPlanQty'];
									if (item.JobPROCID == row.JobPROCID) {
										item['TableData'].push(row)
									}
								})
							});
							// 如果ds2有数据，说明有派工记录，处理派工
							if (ret.data.ds2.length) {
								config.assignVal = true;


								let FilterData_Table = FunData.filter((item : any) => {
									return item.TableData.length
								})

								tableData.value = FilterData_Table[0]['TableData']
							}
							RoutingData.value = FunData;

							break;
						default:
							break;
					}

				}
			}
		})
	}

	function GetXGD_JobGetWOProcedure() {

	}

	onLoad((option : any) => {
		// 新增 -- 发放派工
		if (uni.$utils.isEmpty(option)) {
			// 获取当前时间
			formData.BillDate = dateFormat();

			// 获取工单传入的数据
			let param_ticket = ticketStore.createTicket_routing;
			console.log(param_ticket);

			// 判断是否存在数据
			if (!uni.$utils.isEmpty(param_ticket)) {
				param_ticket['form']['TypeName'] = '派工单';
				param_ticket['form']['JobDocTypeID'] = 1;
				// 主表数据赋值
				Object.assign(formData, param_ticket['form']);

				console.log(formData.JobOrderID);

				RoutingData.value = param_ticket['ProgressList'].map((item : any) => {
					return {
						...item,
						TableData: []
					}
				});

				let index = RoutingData.value.findIndex((obj : any) => !obj.Outsource);
				if (index >= 0) {
					changeCurrent({}, index);
				}

				// 将工艺路线名称数据提取出来 用 '、' 分割
				let GetRouting = param_ticket['ProgressList'].map((item : any) => {
					return item.ProcedureName
				})
				formData.Routing = GetRouting.join('、');

			}

		} else {
			// 查看派工单明细
			config.isEdit = true;
			console.log(option);
			formData.JobOrderID = option.JobOrderID
			getDispatchInfo('all');
		}
	});

	onReady(() => {
		console.log(formData.JobOrderID);
		uni.$on(formBaseScreenListenName.value, (ret : any) => {
			console.log(ret);
			switch (ret.titleName) {
				case "派工类型":
				case "产品":
					Object.assign(formData, ret.data);
					break;
				case "来源工单":
					Object.assign(formData, {
						WoOrderID: ret.data.WoOrderID,
						BillNO: ret.data.BillNO,
						ProductID: ret.data.ProductID,
						ProductName: ret.data.ProductName,
						ProductSpec: ret.data.ProductSpec,
						ProductCode: ret.data.ProductName + '|' + ret.data.ProductSpec,
						FPlanQty: ret.data.KFPlanQty,
					});
					GetXGD_JobGetWOProcedure();
					break;
				case "工艺路线":
					console.log(ret.data);

					let backData = ret.data;

					RoutingData.value = ret.data;
					// 如果选中的数据，超出工艺长度，设为0
					if (backData.length < stepsCurrent.value) {
						stepsCurrent.value = 0;
					};
					console.log(backData[stepsCurrent.value]);

					tableData.value = backData[stepsCurrent.value]['TableData'];

					// 将工艺路线名称数据提取出来 用 '、' 分割
					let GetRouting = backData.map((item : any) => {
						return item.ProcedureName
					})
					formData.Routing = GetRouting.join('、');

					setTimeout(() => {
						baseFormRef.value.validate();
					}, 50);

					break;
				default:
					break;
			};
		});

		uni.$on(childBaseScreenListenName.value, (ret : any) => {
			switch (ret.titleName) {
				case "派工类型":
				case "设备":
					Object.assign(tableData.value[clickCellInfo.index], ret.data);
					break;
				default:
					break;
			};
		});
	});

	const instance = getCurrentInstance() as any;
	const query = uni.createSelectorQuery().in(instance.proxy);
	let stickyHeight = ref(0);
	// 获取表格容器高度
	const getTableHeight = () => {
		query.select('#sticky-box').fields({
			size: true
		}, (sticky : any) => {
			console.log(sticky);
			stickyHeight.value = sticky.height + 20;
		}).exec();
	};


	watch(() => config.assignVal, (nval) => {
		console.log(nval);
		if (nval) {
			// 判断高度是否计算过，未计算过开启计算
			if (stickyHeight.value == 0) {

				setTimeout(() => {
					getTableHeight();
				}, 300);
			}
		}
	});


	onMounted(() => {
		console.log(config.assignVal);
		// 如果是指派的，先获取数据
		if (config.assignVal) {
			// 获取容器高度设置表格高度
			setTimeout(() => {
				getTableHeight();
			}, 300);
		}
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;

		&__main {
			background-color: #f9f9f9;

			:deep(.u-sticky) {
				background-color: #fff !important;
				padding: 10px 10px;

				.assignVal {
					font-size: 15px;
					color: #303133;
					width: 100px;
					margin-right: 15rpx;
				}

				.setps__box {
					background-color: #fff;
					width: 100%;
					overflow: auto;
					padding: 20rpx 0 10rpx;
				}
			}
		}
	}
</style>